package com.coalmine.api.service.impl;


import cn.hutool.core.util.StrUtil;
import com.coalmine.api.domain.*;
import com.coalmine.api.service.*;
import com.coalmine.api.util.JdbcUtil;
import com.coalmine.common.exception.user.SQLParamException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.*;

/**
 * <p>
 * api的审批信息表 服务实现类
 * </p>
 *
 * @author 尚郑
 * @since 2022-06-02
 */
@Service
public class ApiResourceServiceImpl implements IApiResourceService {

    @Autowired
    private IApiTokenService tokenService;

    @Autowired
    private IApiGroupService apiGroupService;

    @Autowired
    private IApiConfigService apiService;

    @Autowired
    private IApiDatasourceService dataSourceService;

    @Autowired
    private IApiApproveService approveService;

    @Value("${datamanage.api.context}")
    String apiContext;

    @Override
    public Map<String, Object>
    getDetail(ApiConfig apiConfig, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        // 获取tokenId
        String tokenId = request.getHeader("id");
        // 查询是否授权
        boolean auth = tokenService.checkToken(apiConfig.getPath(), tokenId);
        map.put("auth",auth);
        map.put("groupId",apiConfig.getGroupId());
        map.put("path", request.getServerName() + ":" + request.getServerPort() + "/" +  apiContext + "/" + apiConfig.getPath());
        map.put("note", apiConfig.getNote());
        map.put("contentType", apiConfig.getContentType());
        map.put("previlege", apiConfig.getPrevilege());
        if (MediaType.APPLICATION_JSON_VALUE.equals(apiConfig.getContentType())){
            map.put("params",apiConfig.getJsonParam());
        }else {
            map.put("params",apiConfig.getParams());
        }
        map.put("updateTime",apiConfig.getUpdateTime());
        List<ApiSql> sqlList = apiService.getSqlByConfigId(apiConfig.getId());
        // 获取数据源
        ApiDatasource apiDatasource = dataSourceService.detail(apiConfig.getDatasourceId());
        List<Map<String,String>> apiResult = new ArrayList<>();
        sqlList.stream().forEach(apiSql -> {
            try {
                // 组装多个返回结果
                List<Map<String, String>> sqlResult = JdbcUtil.getSqlResult(apiDatasource, apiSql.getSqlText(),null);
                sqlResult.stream().forEach(stringMap ->{
                    apiResult.add(stringMap);
                });

            } catch (SQLException throwables) {

                throw new SQLParamException("获取返回说明异常!");
            }
        });
        map.put("apiResult",apiResult);
        return map;
    }

    @Override
    public Map<String, Object> getIndex(List<Map> apiGroupList) {
        Map<String, Object> map = new HashMap<>();
        map.put("apiGroupList", apiGroupList);
        // 查询最新资源
        List<Map> newResList = apiService.getNewestList();
        map.put("newResList", newResList);
        List<Map> hotResList = apiService.getHotList();
        map.put("hotResList", hotResList);
        return map;
    }

    @Override
    public ApiToken getToken(String name, String password) {
        return tokenService.getToken(name, password);
    }

    @Override
    public List<Map> getAllGroup() {
        return apiGroupService.getAllGroup();
    }

    @Override
    public ApiConfig getById(String id) {
        return apiService.getById(id);
    }

    @Override
    public Map<String, Object> getInfo(List<Map> apiGroupList) {
        Map<String, Object> map = new HashMap<>();
        // 获取组下的资源
        apiGroupList.stream().forEach(group -> {
            String groupid = String.valueOf(group.get("groupid"));
            if (StrUtil.isNotBlank(groupid)) {
                List<Map> apiList = apiService.getByGroupId(groupid);
                group.put("children", apiList);
            }
        });
        map.put("apiGroupList", apiGroupList);
        return map;
    }

    @Override
    public List<Map> searchResource(String name, String apiId, String groupId) {
        return apiService.searchResource(name, apiId, groupId);
    }

    @Override
    public int apply(String applyReason, String groupId, String tokenId, String apiId) {
        ApiApprove apiApprove = new ApiApprove();
        apiApprove.setGroupId(groupId);
        apiApprove.setTokenId(tokenId);
        apiApprove.setApplyTime(new Date());
        apiApprove.setApplyReason(applyReason);
        apiApprove.setApproveType(0);
        apiApprove.setApiId(apiId);
        return approveService.apply(apiApprove);
    }

    @Override
    public String searchResourceCount() {
        return apiService.searchResourceCount();
    }
}
